/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.web.service;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.tools.utils.LotteryUtil;
import com.jeeplus.modules.web.entity.WxGoods;
import com.jeeplus.modules.web.entity.WxGoodsRecord;
import com.jeeplus.modules.web.entity.WxUser;
import com.jeeplus.modules.web.mapper.WxGoodsMapper;
import com.jeeplus.modules.web.mapper.WxGoodsRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 奖品管理Service
 * @author rongjie
 * @version 2017-09-04
 */
@Service
@Transactional(readOnly = true)
public class WxGoodsRecordService extends CrudService<WxGoodsRecordMapper, WxGoodsRecord> {

	@Autowired
	private WxGoodsMapper wxGoodsMapper;

	public WxGoodsRecord get(String id) {
		return super.get(id);
	}
	
	public List<WxGoodsRecord> findList(WxGoodsRecord wxGoodsRecord) {
		return super.findList(wxGoodsRecord);
	}
	
	public Page<WxGoodsRecord> findPage(Page<WxGoodsRecord> page, WxGoodsRecord wxGoodsRecord) {
		return super.findPage(page, wxGoodsRecord);
	}
	
	@Transactional(readOnly = false)
	public void save(WxGoodsRecord wxGoodsRecord) {
		super.save(wxGoodsRecord);
	}
	
	@Transactional(readOnly = false)
	public void delete(WxGoodsRecord wxGoodsRecord) {
		super.delete(wxGoodsRecord);
	}

	@Transactional(readOnly = false)
	public void createGoodsRecord(String orderNumber,String userId,String money){
		//根据充值金额获取中奖概率
		List<WxGoods> wxGoodsRate = wxGoodsMapper.getWxGoodsRate(money);
		if(wxGoodsRate!=null && wxGoodsRate.size() >0){
			List<Double> orignalRates = new ArrayList<>(wxGoodsRate.size());
			for (WxGoods wxGoods : wxGoodsRate) {
				double probability = Double.valueOf(wxGoods.getGoodsRate())/100;
				if (probability < 0) {
					probability = 0;
				}
				orignalRates.add(probability);
			}
			int orignalIndex = LotteryUtil.lottery(orignalRates);
			WxGoods wxGoods = wxGoodsRate.get(orignalIndex);
			WxGoodsRecord wxGoodsRecord = new WxGoodsRecord();
			wxGoodsRecord.setMoney(new BigDecimal(money));
			wxGoodsRecord.setOrderNumber(orderNumber);
			wxGoodsRecord.setWxGoods(wxGoods);
			WxUser wxUser = new WxUser();
			wxUser.setId(userId);
			wxGoodsRecord.setWxUser(wxUser);
			mapper.insert(wxGoodsRecord);
			wxGoodsMapper.setGoods(wxGoods);
		}

	}
}